package com.sp.homework;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Homework02SenderB {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(9998);

        //发送数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入问题:");
        String question = scanner.next();
        byte[] data = question.getBytes();
        DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.0.101"), 8888);
        socket.send(packet);


        //接收数据
        //1. 构建一个DatagramPacket对象, 接收数据
        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);
        //2. 调用接收方法, 将通过网络传输的DatagramPacket对象填充到packet对象
        socket.receive(packet);
        //3. 把packet进行拆包, 取出数据, 并显示
        String s = new String(packet.getData(), 0, packet.getLength());
        System.out.println(s);

        socket.close();
        System.out.println("发送端退出");
    }
}
